package com.algorithm.ocean.leetcode;

import org.junit.Test;

import java.util.Arrays;

/**
 * 两数之和
 * 题目地址：https://leetcode-cn.com/problems/two-sum/
 *
 * @author PF.Tian
 * @since 2022/2/25
 */
public class Len001 {

    /**
     * 自己做的
     */
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        a:
        for (int i = 0; i < nums.length; i++) {
            for (int j = nums.length - 1; j > i; j--) {
                if (nums[i] + nums[j] == target) {
                    result[0] = i;
                    result[1] = j;
                    break a;
                }
            }
        }
        return result;
    }

    @Test
    public void runTowSum() {
        Len001 len001 = new Len001();
        int[] nums = {2, 7, 11, 15};
        int target = 9;
        int[] ints = len001.twoSum(nums, target);
        System.out.println(Arrays.toString(ints));

    }

    /**
     * 官方
     */
    public int[] twoSum2(int[] nums, int target) {
        int sum = nums.length;
        for (int i = 0; i < sum; i++) {
            for (int j = i + 1; j < sum; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return null;
    }

    @Test
    public void runTowSum2() {
        Len001 len001 = new Len001();
        int[] nums = {2, 7, 11, 15};
        int target = 9;
        int[] ints = len001.twoSum2(nums, target);
        System.out.println(Arrays.toString(ints));
    }


}
